<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Session;
class LoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return view('/admin/login');
    }

    public function doaction(Request $request)
    {

        //获取用户输入的信息
        $account=$request->input('account');
        $password=md5($request->input('password'));
        $vode =$request->input('vcode');

        if($vode!=session('vcode')){


         return  back()->with('error','验证码不正确');
        
        }

        //根据用户输入信息查询 昵称 状态 id
        $res = DB::table('ug_user')
               ->where('account','=',$account)
               ->where('password','=',$password)
               ->select('nickname','status','id')
               ->first();

                //判断用户密码 账号 是否匹配 状态是否符合进入后台的标准
                if($res&&$res->status==2){
                    $username=DB::table('ug_user_details')->where('uid',$res->id)->select('username')->first()->username;
                   if(empty($username))
                   {
                      session(['id'=>$res->id,'username'=>$res->nickname,'status'=>$res->status]);
                      
                   }else{

                      session(['id'=>$res->id,'username'=>$username,'status'=>$res->status]);
                   }
                    

                    return redirect('/admin/User');

                //当用户 状态 或者账号密码 不匹配时 对用户进行重定向
                }elseif($res&&$res->status==1){

                    return  back()->with('error','权限不足!!!');

                 }else{

                    return  back()->with('error','账户名或密码错误');
                }      
    }

      /**
      * 退出登录的方法
      */
      public function logout(Request $request)
      {
                session(['id'=>null,'status'=>null,'nickname'=>null]);

               
                return redirect('/admin');
      }    

      /**
      *
      * 生成验证码的方法
      */     
      public function vcode(Request $request)
      {
           //生成验证码图片的Builder对象，配置相应属性
            $builder = new CaptchaBuilder;
            //可以设置图片宽高及字体
            $builder->build($width = 100, $height = 40, $font = null);
            //获取验证码的内容
            $phrase = $builder->getPhrase();

            //把内容存入session
            // Session::flash('vcode', $phrase);
            session(['vcode'=>$phrase]);
            //生成图片
            header("Cache-Control: no-cache, must-revalidate");
            header('Content-Type: image/jpeg');
            $builder->output();
      }
}
